require "Common/define"
require "Logic/CtrlManager"
require "Logic/Config"
require "Net/roleListHandler"
require "Net/Innatehandler"
require "proto/player/message/ReqSettleMessage"
require "proto/player/message/ReqModifyPersonMessage"
require "proto/roleinfo/message/ReqModifyFormationMessage"
require "proto/roleinfo/message/ReqModifyPicMessage"
require "proto/roleinfo/message/ReqModifyBackgroundMessage"
require "proto/others/message/ReqOtherRoleInfoMessage"
require "proto/star/message/ReqReplaceCityBackgroundMessage"
require "model/RoleAttributeModel"
require "model/MercenAttributeModel"

roleInfoHandler = roleInfoHandler or {};
G.serverData = G.serverData or {};

local autoCalcuExpTimer;

function roleInfoHandler.startCalculateExp()

    if autoCalcuExpTimer == nil then
        autoCalcuExpTimer = Timer.New(roleInfoHandler.updateExpCoinClient, 60, 999999, false);
    else
        autoCalcuExpTimer:Reset(roleInfoHandler.updateExpCoinClient, 60, 999999, false);
    end
    autoCalcuExpTimer:Start();

end

function roleInfoHandler.updateExpCoinClient()

    if G.serverData["roleInfo"] == nil or G.serverData["mapInfo"] == nil then
        return ;
    end

    if G.serverData["roleInfo"].show.nextexp > 0 then
        local addexp = Mathf.Floor(G.dataTable["T_map"][tostring(G.serverData["mapInfo"].map_id)].f_MapEXP);
        G.serverData["roleInfo"].show["exp"] = G.serverData["roleInfo"].show["exp"] + addexp;
        if G.serverData["roleInfo"].show["exp"] >= G.serverData["roleInfo"].show.nextexp then

            --local reqsettle = ReqSettleMessage.New();
            --sendReqMessage(reqsettle,0);
            return ;
            --G.serverData["roleInfo"].show["level"] = G.serverData["roleInfo"].show["level"] + 1;
            --G.serverData["roleInfo"].show["exp"] = G.serverData["roleInfo"].show["exp"] - G.serverData["roleInfo"].show.nextexp;
            --G.serverData["roleInfo"].show["nextexp"] = G.dataTable["T_characterexp"][tostring(G.serverData["roleInfo"].show["level"])].f_CharacterExp;
        end
    end

    -- local addcoin =  Mathf.Floor(G.dataTable["T_map"][tostring(G.serverData["mapInfo"].map_id)].f_MapCoin);
    -- G.serverData["roleInfo"].currencyAttributes[CurrencyEnum.MONEY].value = G.serverData["roleInfo"].currencyAttributes[CurrencyEnum.MONEY].value + addcoin;
    FireEvent(Config.EventType.Fresh_Currency);

end
--新协议
function roleInfoHandler.onGetRoleInfo(msg)
    print("=====================收到角色信息");

    G.serverData["roleInfo"] = G.serverData["roleInfo"] or {};

    G.serverData["roleInfo"].show = msg.show;
    G.serverData["roleInfo"].show.playerId = G.serverData["roleInfo"].show.playerId:tostring();
    G.serverData["roleInfo"].show["exp"] = 0;
    G.serverData["roleInfo"].show["nextexp"] = G.dataTable["T_characterexp"][MakeTopLevelId(msg.show.level)].f_CharacterExp;
    G.serverData["roleInfo"].currencyAttributes = {};


    local roleinfo = G.serverData["roleInfo"].show.playerId .. "," .. G.serverData["roleInfo"].show.name .. "," .. "区服名" .. "," .. msg.show.level;

    if AppConst.isBussiness == 0 then
        LoginSDK.GetInstance():startGameSDK(roleinfo);
    end

    -- TDGABehavior.SetGameServer(msg.serverId);
    -- TDGABehavior.SetLevel(msg.show.level);

    for i = 1, #msg.currencyAttributes do
        local attribute = {};
        attribute.type = msg.currencyAttributes[i].type;
        attribute.value = tonumber(msg.currencyAttributes[i].value:tostring());
        G.serverData["roleInfo"].currencyAttributes[attribute.type] = attribute;
    end

    --IMAudioMgr:loginIMSystem(G.serverData["roleInfo"].show.playerId);
    if G.serverData["roleInfo"].strengthInfo == nil then
        G.serverData["roleInfo"].strengthInfo = {};
        for i = 1, 6 do
            G.serverData["roleInfo"].strengthInfo[i] = 0;
        end
    end

    roleInfoHandler.updateRoleSkill();
    --mapMgr:FreshRoleData(getJsonStr(G.serverData["roleInfo"].show));

    roleInfoHandler.startCalculateExp();
    RoleAttributeModel.updateLevelAttribute();
    FireEvent(Config.EventType.Fresh_UILock);

end

function roleInfoHandler.updateRoleSkill()
    if G.serverData["roleInfo"] == nil then
        return ;
    end
    G.serverData["roleSkill"] = G.serverData["roleSkill"] or {};
    --local rolelevel = G.serverData["roleInfo"].show.level;
    --local roleProf = G.serverData["roleInfo"].show.leaderModelId;
    --
    --local rolecfg = G.dataTable["T_character"][roleProf.."_"..rolelevel].f_skill;
    --G.serverData["roleSkill"] = decodeJsonStrToTabel(rolecfg);
    --Innatehandler.UpDateSkillForMainPlayerLvUP();
    --mapMgr:UpdateHeroEquipSkills(rolecfg);

end

function roleInfoHandler.updateAllRoleInfo(msg)

    G.serverData["lastSettleTime"] = tonumber(msg.settleTime:tostring());
    G.serverData["expPool"] = tonumber(msg.expPool:tostring());

    for i = 1, #msg.partners do

        local mid = msg.partners[i].partnerId:tostring();
        if G.serverData["roleInfo"] ~= nil and G.serverData["roleInfo"].show.playerId == mid then
            G.serverData["roleInfo"].show.exp = tonumber(msg.partners[i].exp:tostring());
            if tonumber(msg.partners[i].level) > G.serverData["roleInfo"].show.level then
                FireEvent(Config.EventType.Level_Up);

                local roleinfo = G.serverData["roleInfo"].show.playerId .. "," .. G.serverData["roleInfo"].show.name .. "," .. "区服名" .. "," .. G.serverData["roleInfo"].show.level;
                if AppConst.isBussiness == 0 then

                    LoginSDK.GetInstance():upLevelSDK(roleinfo);

                end
                -- TDGABehavior.SetLevel(G.serverData["roleInfo"].show.level);

            end
            G.serverData["roleInfo"].show.level = tonumber(msg.partners[i].level);
            G.serverData["roleInfo"].show["nextexp"] = G.dataTable["T_characterexp"][MakeTopLevelId(G.serverData["roleInfo"].show.level)].f_CharacterExp;

        elseif MercenaryModel.mercenSotreList[mid] ~= nil then
            local isLvUp = false;
            UIWaiting.HideWaiting();
            if MercenaryModel.mercenSotreList[mid]["level"] ~= 0 and MercenaryModel.mercenSotreList[mid]["level"] < msg.partners[i].level then
                -- 升级了
                showUI(PanelNames.UICommonHeroUp, msg.partners[i].level, MercenaryModel.mercenSotreList[mid]["partnerId"])
                UISysTips.AddMsg("伙伴等级升级成功！")
                isLvUp = true;
                --AudioManager.Play(2001)
            end
            MercenaryModel.mercenSotreList[mid]["level"] = msg.partners[i].level;
            MercenaryModel.mercenSotreList[mid]["attribute"]:Updata(MercenaryModel.mercenSotreList[mid]);
            MercenaryModel.mercenSotreList[mid]["exp"] = tonumber(msg.partners[i].exp:tostring());
            MercenaryModel.mercenSotreList[mid]["star"] = msg.partners[i].star;
            if isLvUp then
                FireEvent(Config.EventType.Fresh_HeroLv);
            end

        end

    end

    if G.serverData["teamInfo"] ~= nil then
        local teammembers = G.serverData["teamInfo"].members;

        for i = 1, #teammembers do
            local teamMember = teammembers[i];
            if #(tostring(teamMember.playerId)) == 1 or teamMember.playerId == G.serverData["roleInfo"].show.playerId then
                teamMember.lead.level = G.serverData["roleInfo"].show.level;
            end
        end

    end
    RoleAttributeModel.updateLevelAttribute();

    --mapMgr:updateRoleAttack(RoleAttributeModel.totalAttribute[EnumConst.FighterAttributeEnum.ATK])

    --if MercenaryModel.fightID ~= nil and MercenaryModel.mercenSotreList[MercenaryModel.fightID] ~= nil then
    --mapMgr:updateMercenAttack(MercenaryModel.mercenSotreList[MercenaryModel.fightID]["attribute"].totalAttribute[EnumConst.FighterAttributeEnum.ATK])
    --end
    roleInfoHandler.updateRoleSkill();

    FireEvent(Config.EventType.Fresh_Currency);

    FireEvent(Config.EventType.Fresh_Team);
    FireEvent(Config.EventType.Fresh_UILock);

end
function roleInfoHandler.updateCurrencyInfo(msg)
    print("经验或者货币改变");
    local currencytype = msg.attributes.type;
    if G.serverData["roleInfo"] ~= nil and G.serverData["roleInfo"].currencyAttributes[currencytype] ~= nil then
        G.serverData["roleInfo"].currencyAttributes[currencytype].value = tonumber(msg.attributes.value:tostring());
        FireEvent(Config.EventType.Fresh_Currency);
    end

end

function roleInfoHandler.updateRoleEquipedSkill(msg)

    --local equipSkill = msg.skillItemId;
    G.serverData["equipSkill"] = msg.skillId;
    --[[    for i=1,#equipSkill do
            table.insert(G.serverData["equipSkill"],equipSkill[i]:tostring());
        end]]

end

function roleInfoHandler.changeRoleEquipedSkill(msg)

    if msg.state == 0 then

        G.serverData["equipSkill"] = msg.skillId;
        FireEvent(Config.EventType.Fresh_EquipedSkill);

    end

end
function roleInfoHandler.updateRoleSkillField(msg)

    if msg.state == 0 then
        local fieldid = msg.fieldId;
        local roleid = G.serverData["roleInfo"].show.playerId;
        if G.serverData["roleSkillField"][roleid] ~= nil then
            G.serverData["roleSkillField"][roleid][fieldid + 1].exp = tonumber(msg.exp:tostring());
            G.serverData["roleSkillField"][roleid][fieldid + 1].level = msg.level;
        end
        FireEvent(Config.EventType.Fresh_EquipedSkill);
    end
end
function roleInfoHandler.addExp(expnum)

    if G.serverData["roleInfo"] ~= nil then
        G.serverData["roleInfo"].show.exp = G.serverData["roleInfo"].show.exp + expnum;
    end

end

function roleInfoHandler.sendreqOtherRoleInfo(otherID, showHello)
    local rdtr = ReqOtherRoleInfoMessage.New();
    rdtr.queryPlayerId = otherID;
    roleInfoHandler.showHello = showHello;
    sendReqMessage(rdtr);
end

function  roleInfoHandler.ResOtherRoleInfo(msg)
    local info = {}
    info.data = msg;
    FireEvent(Config.EventType.FreashRoleInfoOther, info);

end

function roleInfoHandler.SendReqModifyFomationMessage(formation)
    local rdtr = ReqModifyFormationMessage.New();
    rdtr.formation = formation;
    sendReqMessage(rdtr);
end

function roleInfoHandler.SendReqModifyPicMessage(spic, frame)
    frame = frame or logicMgr.HeroManager.GetRoleInfo("picFrame")  --0代表  不修改头像框
    local rdtr = ReqModifyPicMessage.New()
    rdtr.pic = spic
    rdtr.frame =frame;
    sendReqMessage(rdtr)
end

function roleInfoHandler.SendReqModifyBackgroundMessage(spic)
    local rdtr = ReqModifyBackgroundMessage.New()
    rdtr.background = tonumber(spic)
    sendReqMessage(rdtr)
end

function roleInfoHandler.RecvModifyPic(msg)
    if msg.state == 0 then
        logicMgr.HeroManager.SetRoleHeadID(toNumber(logicMgr.SkinManager.getHeroModelIdBySkinId(msg.pic)))
        logicMgr.HeroManager.SetRoleInfo("pic",toNumber(msg.pic))
        G.serverData["roleInfo"].show.picFrame = msg.frame;
        FireEvent(Config.EventType.FreashRoleShowDraw)
        chatHandler.SendCityPlayerInfo()
        HeroManager.RefreshHeadFrameAtt()
        partnerHandler.ReqHeroPower(0)
    end
end

function roleInfoHandler.RecvModifyBackGround(msg)
    if msg.state == 0 then

    end
end

function roleInfoHandler.RecvModifyFomation(msg)
    if msg.state == 0 then
        G.serverData["roleInfo"].show.formation = msg.formation;

        FireEvent(Config.EventType.FreashRoleInfo, nil);
    end
end

--- 修改名称/性别
function roleInfoHandler.R_ModifyPerson(name, sex)
    local req = ReqModifyPersonMessage.New()
    req.name = name or ""
    req.sex = sex or 0
    sendReqMessage(req)
end

function roleInfoHandler.S_ModifyPerson(name, sex, modifyCount)
    local _nameDic = {}
    _nameDic.old_name = tostring(HeroManager.GetRoleName())
    _nameDic.new_name = tostring(name)
    if _nameDic.old_name ~= _nameDic.new_name then
        TAManager.TrackByDictionary("modify_role_name",_nameDic)

        -- iOS Widget: 更新玩家昵称
        if CompareOriginVersion("1.4.2.0001") then
            LoginSDK.GetInstance():SetWidgetUserNick(_nameDic.new_name)
        end
    end

    local _sexDic = {}
    _sexDic.old_sex = tonumber(HeroManager.GetRoleSex())
    _sexDic.new_sex = tonumber(sex)
    if _sexDic.old_sex ~= _sexDic.new_sex then
        TAManager.TrackByDictionary("modify_role_sex",_sexDic)
    end

    logicMgr.HeroManager.SetRoleInfo("name", name)
    logicMgr.HeroManager.SetRoleInfo("sex", sex)
    logicMgr.HeroManager.SetRoleInfo("modifyCount", modifyCount)
    FireEvent(Config.EventType.FreashRoleInfo)
    FireEvent(Config.EventType.Show_HeadMenu_HeadIcon)
    chatHandler.SendCityPlayerInfo()
    local ctrl = CtrlManager.GetCtrl(PanelNames.UIHeadInfo);
    if ctrl then
        ctrl.HideChangeName()
    end
    UISysTips.AddMsg(getLanguage("Sys_MsgConfigUpdated"));
end

--- 修改主城背景
function roleInfoHandler.ReqReplaceCityBackground(bgId)
    local req = ReqReplaceCityBackgroundMessage.New()
    req.cityBackground = bgId
    sendReqMessage(req)
end
function roleInfoHandler.ResReplaceCityBackground(msg)
    if msg.state ~= 0 then return end
    G.serverData['cityBg'] = msg.cityBackground
end